<?php


namespace app\crontab\controller\always;


use app\common\lib\RespCode;
use custom\Log;
use push\Aurora2;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;

/**
 * 推送系统消息
 * Class MessageAgentSystem
 * @package app\crontab\controller
 */
class MessageAgentSystem extends Command {

    protected function configure() {
        $this->setName('MessageAgentSystem');
    }

    protected function execute(Input $input, Output $output) {
        try {
            echo "start\n";
            //未推送的系统消息
            $message_system = db("message_system")
                ->where('is_push', 0)
                ->field('title,content,pic,link_title,link,type')
                ->select();
            if (empty($message_system)) {
                throw new  Exception('无需处理', RespCode::PARAMS_ERR);
            }
            //待推送的经纪人id
            $agentid = db("company_agent")
                ->where('deleted', 0)
                ->field('registration_id,id')
                ->select();
            if (empty($agentid)) {
                throw new  Exception('无需处理', RespCode::PARAMS_ERR);
            }
            $merge = [];
            foreach ($agentid as $v) {
                foreach ($message_system as $index1 => $item1) {
                    $message_system[$index1]['agent_id'] = $v['id'];
                    $message_system[$index1]['is_read'] = 0;
                    $message_system[$index1]['itime'] = time();
                }
                $merge = array_merge($merge, $message_system);
                foreach ($merge as $k1 => $v1) {
                    if (Db::name('message_agent_system')->insert($v1) !== false) {
                        if (!empty($v['registration_id'])) {
                            $cids = Aurora2::getCid($v['id']);
                            //推送
                            if (!Aurora2::push($cids[0], $v['registration_id'], $v1['title'], Aurora2::TYPE1))
                                throw new  Exception('推送失败:设备号->' . $v['registration_id'] . '|' . $v['id'], RespCode::PARAMS_ERR);
                        }
                    }
                }
                $merge = [];
            }
            //更新为已推
            db("message_system")
                ->where('is_push', 0)
                ->update(['is_push' => 1]);
            echo "end\n";
        } catch (Exception $e) {
            Db::close();
            $err = "异常信息:{$e->getMessage()} | 所在的代码行:{$e->getFile()} | 文件{$e->getFile()} | php 版本 " . PHP_VERSION . "(" . PHP_OS . ")";
            Log::write($err, "MessageAgentSystem_Err.log");
        }
    }

}
